package org.dromara.web.websocket;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.web.websocket.request.SubscribeRequest;
import org.dromara.websocket.connection.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Create Date      2023-09-28
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */

@Slf4j
@Service
public class SubscribeConnectionHolder extends ConnectionHolder {

    private HashMap<String, List<Connection>> topics = new HashMap<>();
    private HashMap<Connection, List<String>> connections = new HashMap<>();

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;


    public static final String TOPIC_FRONT = "front";

    public static final String TOPIC_ADMIN = "admin";

    public static final String TOPIC_AGENT = "agent";

    public static final String TOPIC_GENERATOR = "generator";

    /**
     * 前端发送订阅消息
     *
     * @param request
     */
    public synchronized void onSubscribe(Connection connection, SubscribeRequest request) {
        log.info("收到订阅: {}", JsonUtils.toJsonString(request));
        if (StringUtils.isEmpty(request.getTopic())) return;
        List<String> tops = connections.get(connection);
        if (tops == null) {
            tops = new ArrayList<>();
            connections.put(connection, tops);
        }
        tops.add(request.getTopic());
        List<Connection> conn = topics.get(request.getTopic());
        if (conn == null) {
            conn = new ArrayList<>();
            topics.put(request.getTopic(), conn);
        }
        conn.add(connection);
    }


    public synchronized void deSubscribe(Connection connection, SubscribeRequest request) {
        List<String> tops = connections.get(connection);
        if (CollectionUtils.isNotEmpty(tops)) {
            tops.remove(request.getTopic());
        }
        List<Connection> conn = topics.get(request.getTopic());
        if (CollectionUtils.isNotEmpty(conn)) {
            conn.remove(connection);
        }
    }


    @Override
    public synchronized void onConnectionRemoved(Connection connection) {
        List<String> tops = connections.remove(connection);
        if (CollectionUtils.isNotEmpty(tops)) {
            tops.stream().forEach(top -> {
                List<Connection> conn = topics.get(top);
                if (CollectionUtils.isNotEmpty(conn)) {
                    conn.remove(connection);
                }
            });
        }
    }




    /**
     * 给我定的topic推送消息
     *
     * @param topic
     * @param payload
     */
    private void push(String topic, Payload payload) {
        try {
            if (StringUtils.isEmpty(topic)) return;
            List<Connection> conn = topics.get(topic);
            if (CollectionUtils.isNotEmpty(conn)) {
                conn.forEach(connection -> {
                    connection.push(JSON.toJSONString(payload));
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
